package com.wh.wisdomsite.xbox.server.controller.st;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.wh.wisdomsite.xbox.common.util.ResManager;
import com.wh.wisdomsite.xbox.pojo.st.PurchaseApplyIn;
import com.wh.wisdomsite.xbox.pojo.st.PurchaseDetailIn;
import com.wh.wisdomsite.xbox.server.util.UserUtils;
import com.wh.wisdomsite.xbox.st.entity.PurchaseApply;
import com.wh.wisdomsite.xbox.st.entity.PurchaseDetail;
import com.wh.wisdomsite.xbox.st.service.IPurchaseApplyService;
import com.wh.wisdomsite.xbox.st.service.IPurchaseDetailService;
import com.wh.wisdomsite.xbox.utils.date.DateTool;
import com.wh.wisdomsite.xbox.utils.json.JsonUtil_Org;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;


/**
 * 采购更新controller
 * @author 杨世强
 * @version V1.0
 * @Package com.wh.wisdomsite.xbox.server.controller.st
 * @date 2019年1月2日 10:39
 * @Copyright 企业版权所有
 * @Company 贵州万华科技有限公司Copyright (c) 2018
 */
@Controller
@RequestMapping(value = "/purchaseSchedule")
public class PurchaseScheduleController {
    private static final Log logger = LogFactory.getLog(PurchaseApplyController.class);

    @Autowired
    private IPurchaseApplyService iPurchaseApplyService;

    @Autowired
    private IPurchaseDetailService iPurchaseDetailService;

    /**
     * 页面跳转
     *
     * @return
     */
    @RequiresPermissions("rules:st_purchaseSchedule_page")
    @RequestMapping(value = "index.do", method = RequestMethod.GET)
    public String index() {
        return "/st/purchaseSchedule/scheduleList";
    }

    /**
     * 获取已审核数据集合
     *
     * @param response
     * @param in
     */
    @RequiresPermissions("rules:st_purchaseSchedule_find")
    @RequestMapping(value = "/scheduleList.do")
    public void scheduleList(HttpServletResponse response, PurchaseApplyIn in) {
        try {
            logger.info("加载已审核请购列表-->>开始");
            //设置分页
            if (in.getPage() == 0) in.setPage(1);
            if (in.getRows() == 0) in.setRows(10);
            Page<PurchaseApply> page = new Page<PurchaseApply>();
            page.setCurrent(in.getPage());
            page.setSize(in.getRows());
            //设置条件
            EntityWrapper<PurchaseApply> ewPurchaseApply = new EntityWrapper<PurchaseApply>();
            ewPurchaseApply.setEntity(new PurchaseApply());
            //已审核
            ewPurchaseApply.eq("pur.checkState", '2');
            if (StringUtils.isNotEmpty(in.getStartDate()) && StringUtils.isNotEmpty(in.getEndDate())) {
                ewPurchaseApply.between("pur.purDate", in.getStartDate(), in.getEndDate() + " " + "23:59:59");
            } else if (StringUtils.isNotEmpty(in.getStartDate())) {
                ewPurchaseApply.between("pur.purDate", in.getStartDate(), in.getStartDate() + " " + "23:59:59");
            } else if (StringUtils.isNotEmpty(in.getEndDate())) {
                ewPurchaseApply.between("pur.purDate", in.getEndDate(), in.getEndDate() + " " + "23:59:59");
            }
            if (StringUtils.isNotEmpty(in.getPrName())) {
                ewPurchaseApply.like("p1.prName", in.getPrName());
            }
            if (StringUtils.isNotEmpty(in.getCoNumber())) {
                ewPurchaseApply.like("co.coNumber", in.getCoNumber());
            }
            if (StringUtils.isNotEmpty(in.getCoName())) {
                ewPurchaseApply.like("co.coName", in.getCoName());
            }
            //若不是超级管理员则根据用户权限添加查询条件
            if (!UserUtils.isSysAdmin()) {
                ewPurchaseApply = UserUtils.setEntityWrapper(ewPurchaseApply, "co1", "off1", "p1");
            }
            Page<Map<String, Object>> purchaseApplyPage = iPurchaseApplyService.getReportedPage(page, ewPurchaseApply);
            JSONObject json = new JSONObject();
            JSONArray array = new JSONArray();
            if (purchaseApplyPage.getRecords().size() > 0) {
                for (Map<String, Object> purchaseApply : purchaseApplyPage.getRecords()) {
                    JSONObject object = new JSONObject(purchaseApply);
                    object.put("purDate", DateTool.getFormatByMs(purchaseApply.get("purDate")));
                    if (purchaseApply.get("project") != null) {
                        object.put("project", new JSONObject(purchaseApply.get("project")));
                    }
                    if (purchaseApply.get("contract") != null) {
                        object.put("contract", new JSONObject(purchaseApply.get("contract")));
                    }
                    array.put(object);
                }
            }
            json.put("total", purchaseApplyPage.getTotal());
            json.put("rows", array);
            ResManager.getJsonOut(response).print(json);
            logger.info("加载已审核请购列表-->>结束");
        } catch (Exception e) {
            e.printStackTrace();
            logger.debug("加载已审核请购列表-->>Exception" + e.getMessage());
        }
    }

    /**
     * 跳转到采购进度页面
     * @param request
     * @param purId
     * @return
     */
    @RequiresPermissions("rules:st_purchaseSchedule_scheduleFind")
    @RequestMapping(value = "/toScheduleFind.do")
    public String toScheduleFind(HttpServletRequest request, String purId) {
        request.setAttribute("purId",purId);
        return "st/purchaseSchedule/detailList";
    }

    /**
     * 跳转到进度更新页面
     * @param request
     * @param purId
     * @return
     */
    @RequiresPermissions("rules:st_purchaseSchedule_update")
    @RequestMapping(value = "/toScheduleUpdate.do")
    public String toScheduleUpdate(HttpServletRequest request, String purId) {
        request.setAttribute("purId",purId);
        return "st/purchaseSchedule/updateList";
    }
    /**
     * 跳转到收货入库页面
     * @param request
     * @param purId
     * @return
     */
    @RequiresPermissions("rules:st_purchaseSchedule_confirm")
    @RequestMapping(value = "/toScheduleConfirm.do")
    public String toScheduleConfirm(HttpServletRequest request, String purId) {
        request.setAttribute("purId",purId);
        return "st/purchaseSchedule/confirmList";
    }

    /**
     * 采购进度更新
     * @param response
     * @param purchaseDetailArr
     */
    @RequiresPermissions("rules:st_purchaseSchedule_update")
    @RequestMapping(value = "/save.do",method = RequestMethod.POST)
    public void save(HttpServletResponse response, @RequestBody List<PurchaseDetail> purchaseDetailArr) {
        try{
            logger.info("更新采购-->>开始");
            for(PurchaseDetail pd : purchaseDetailArr){
                String purdId =  pd.getPurdId();
                String purdRemark = pd.getPurdRemark();
                PurchaseDetail purchaseDetail = new PurchaseDetail();
                purchaseDetail.setPurdId(purdId);
                purchaseDetail.setPurdRemark(purdRemark);
                iPurchaseDetailService.updateById(purchaseDetail);
            }
            response.getWriter().write(JsonUtil_Org.returnTrue("更新采购成功！"));
            logger.info("更新采购-->>结束");
        }catch (Exception e){
            e.printStackTrace();
            logger.debug("更新采购-->>Exception" + e.getMessage());
        }
    }


    /**
     * 收货入库
     * @param response
     * @param purchaseDetailArr
     */
    @RequiresPermissions("rules:st_confirm_save")
    @RequestMapping(value = "/confirm.do",method = RequestMethod.POST)
    public void confirm(HttpServletResponse response, @RequestBody List<PurchaseDetailIn> purchaseDetailArr) {
        try {
            logger.info("收货入库-->>开始");
            String userId = UserUtils.getCurrentUser().getUsId();
            iPurchaseDetailService.saveConfirm(purchaseDetailArr,userId);
            response.getWriter().write(JsonUtil_Org.returnTrue("收货入库！"));
            logger.info("收货入库-->>结束");
        } catch (Exception e) {
            e.printStackTrace();
            logger.debug("收货入库-->>Exception" + e.getMessage());
        }

    }

    /**
     * 拼接收货状态JSON串
     * @return
     */
    @RequestMapping(value = "/returnState.do",method = RequestMethod.GET)
    @ResponseBody
    public Object ReturnState() {
        Map<String,Object> map1 = new HashMap<>();
        map1.put("id","1");
        map1.put("text","未收货");

        Map<String,Object> map2 = new HashMap<>();
        map2.put("id","2");
        map2.put("text","已收货");
        List<Object> list = new ArrayList<>();
        list.add(map1);
        list.add(map2);
        return list;
    }
}


